/* eslint-disable no-new */
import React, {
  useCallback, useMemo, useState,
} from 'react';
import forEach from 'lodash/forEach';
import { Terminal } from 'xterm';
import { fit } from 'xterm/lib/addons/fit/fit';
import { observer } from 'mobx-react-lite';
import { Choerodon } from '@choerodon/master';
import { saveAs } from 'file-saver';
import { Icon } from 'choerodon-ui/pro';
import { useInterval, useMount, useUnmount } from 'ahooks';
import 'xterm/dist/xterm.css';
import './index.less';
import { isNil } from 'lodash';
import { checkLog } from '../service';

const term = new Terminal({
  fontSize: 13,
  fontWeight: 400,
  fontFamily: 'monospace',
  disableStdin: true,
});

export default observer((props) => {
  const {
    ids,
    jobName,
    modal,
    projectId,
  } = props;
  const prefixCls = useMemo(() => 'c7n-pipelineManages-codeLog', []);
  const [interval, setInterTime] = useState(5000);
  const [logData, setLogData] = useState('');
  const handleDownloadLog = async () => {
    const blob = new Blob([logData], { type: 'text/plain' });
    const filename = `${jobName}-日志.log`;
    saveAs(blob, filename);
    return false;
  };
  modal.handleOk(handleDownloadLog);
  async function loadData() {
    const res = await checkLog(projectId, ids);
    try {
      if (res) {
        const newRes = res.split(/\n/);
        forEach(newRes, (item) => term.writeln(item));
        setLogData(res);
      } else {
        term.writeln('暂无日志');
      }
      setInterTime(null);
    } catch (e) {
      setInterTime(null);
      Choerodon.handleResponseError(e);
      setInterTime(null);
    }
  }

  const goBottom = () => {
    term.scrollToBottom();
  };

  const goTop = () => {
    term.scrollToTop();
  };

  useMount(() => {
    term.open(document.getElementById('jobLog'));
    fit(term);
  });

  useUnmount(() => {
    term.clear();
  });

  useInterval(() => {
    loadData();
    term.scrollToBottom();
  }, interval, { immediate: true });

  return (
    <>
      <div className={`${prefixCls}-container`}>
        <div className={`${prefixCls} ${prefixCls}-hasBtn`} id="jobLog" />
        <div className={`${prefixCls}-btnGorups`}>
          <div
            onClick={goBottom}
            role="none"
            className={`${prefixCls}-btnGorups-btn ${prefixCls}-btnGorups-btn-following`}
          >
            <Icon type="expand_more" />
            回到底部
          </div>
          <div
            onClick={goTop}
            role="none"
            className={`${prefixCls}-btnGorups-btn ${prefixCls}-btnGorups-btn-top`}
          >
            <Icon type="expand_less" />
            回到顶部
          </div>
        </div>
      </div>
    </>
  );
});
